package com.dream.flutter_app_demo.ttad;

import android.content.Context;
import android.graphics.Color;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.androidquery.callback.AQuery2;
import com.bytedance.sdk.openadsdk.AdSlot;
import com.bytedance.sdk.openadsdk.TTAdConstant;
import com.bytedance.sdk.openadsdk.TTAdNative;
import com.bytedance.sdk.openadsdk.TTFeedAd;
import com.bytedance.sdk.openadsdk.TTImage;
import com.bytedance.sdk.openadsdk.TTNativeAd;
import com.dream.flutter_app_demo.R;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugin.platform.PlatformView;

class TTadFeedView implements PlatformView {
    final private static String TAG = "TTadFeed";

    private Context mContext;
    private TTFrameLayout mTTadFeed;
    private TTAdNative mTTAdNative;

    private Button mCreativeButton;
    private AQuery2 mAQuery;
    private Boolean noScroll = true;

    // 广告参数
    private String mAdType;

    TTadFeedView(Context context, BinaryMessenger messenger, int id, Map<String, String> params) {
        mContext = context;

        // 创建广告容器
        mTTadFeed = new TTFrameLayout(context);
        mTTadFeed.setBackgroundColor(Color.WHITE);

        // 创建TTAdNative对象
        mTTAdNative = TTAdManagerHolder.get().createAdNative(context);
        this.mAQuery = new AQuery2(context);

        try {
            // 广告参数
            mAdType = params.get("adType");

            // 加载广告
            loadTTAd(params.get("posId"));
        } catch (Exception e) {
            Log.e(TAG, "Load Error");
        }
    }

    @Override
    public View getView() {
        return mTTadFeed;
    }

    @Override
    public void dispose() {
        mTTadFeed.removeAllViews();
    }

    private void loadTTAd(String codeId) {
        final AdSlot adSlot = new AdSlot.Builder()
                .setCodeId(codeId)
                .setSupportDeepLink(true)
                .setImageAcceptedSize(640, 320)
                .setAdCount(1)
                .build();

        //请求广告，对请求回调的广告作渲染处理
        mTTAdNative.loadFeedAd(adSlot, new TTAdNative.FeedAdListener() {
            @Override
            public void onError(int code, String message) {
                noScroll = false;
                Log.e(TAG, "load error : " + code + ", " + message);
            }

            @Override
            public void onFeedAdLoad(List<TTFeedAd> ads) {
                //加载成功的回调，容错处理
                if (ads == null || ads.isEmpty()) {
                    Log.e(TAG, "on FeedAdLoaded: ad is null!");
                    return;
                }
                View adView;
                TTFeedAd ad = ads.get(0);
                noScroll = true;

                if (ad == null) {
                    return;
                }

                if (TextUtils.equals(mAdType, "lite")) {
                    adView = LayoutInflater.from(mContext).inflate(R.layout.native_ad_lite, mTTadFeed, false);
                } else {
                    adView = LayoutInflater.from(mContext).inflate(R.layout.native_ad, mTTadFeed, false);
                }

                if (mCreativeButton != null) {
                    //防止内存泄漏
                    mCreativeButton = null;
                }

                // 判断广告类型
                if (ad.getImageMode() != TTAdConstant.IMAGE_MODE_VIDEO) {
                    mTTadFeed.removeAllViews();
                    mTTadFeed.addView(adView);

                    //绑定广告的数据
                    bindData(adView, ad);

                    Log.e(TAG, "load success-imageMode:" + ad.getImageMode());
                }
            }
        });
    }

    @SuppressWarnings("RedundantCast")
    private void bindData(View nativeView, TTFeedAd ttFeedAd) {
        ((TextView) nativeView.findViewById(R.id.tv_native_ad_desc)).setText(ttFeedAd.getTitle());
        ((TextView) nativeView.findViewById(R.id.tv_native_ad_title)).setText(ttFeedAd.getDescription());

        if (ttFeedAd.getImageList() != null && !ttFeedAd.getImageList().isEmpty()) {
            TTImage image = ttFeedAd.getImageList().get(0);
            if (image != null && image.isValid()) {
                mAQuery.id(nativeView.findViewById(R.id.iv_native_image)).image(image.getImageUrl());
            }
        }

        // 穿山甲LOGO
        mAQuery.id(nativeView.findViewById(R.id.iv_native_icon)).image(ttFeedAd.getAdLogo());

        mCreativeButton = (Button) nativeView.findViewById(R.id.btn_native_creative);

        //可根据广告类型，为交互区域设置不同提示信息
        switch (ttFeedAd.getInteractionType()) {
            case TTAdConstant.INTERACTION_TYPE_DOWNLOAD:
                mCreativeButton.setVisibility(View.VISIBLE);
                mCreativeButton.setText("立即下载");
                break;
            case TTAdConstant.INTERACTION_TYPE_DIAL:
                mCreativeButton.setVisibility(View.VISIBLE);
                mCreativeButton.setText("立即拨打");
                break;
            case TTAdConstant.INTERACTION_TYPE_LANDING_PAGE:
            case TTAdConstant.INTERACTION_TYPE_BROWSER:
                mCreativeButton.setVisibility(View.VISIBLE);
                mCreativeButton.setText("查看详情");
                break;
            default:
                mCreativeButton.setVisibility(View.GONE);
                Log.e(TAG, "交互类型异常");
        }

        //可以被点击的view, 也可以把nativeView放进来意味整个广告区域可被点击
        List<View> clickViewList = new ArrayList<>();
        clickViewList.add(nativeView);

        //触发创意广告的view（点击下载或拨打电话）
        List<View> creativeViewList = new ArrayList<>();
        //creativeViewList.add(nativeView);
        creativeViewList.add(mCreativeButton);

        //重要! 这个涉及到广告计费，必须正确调用。convertView必须使用ViewGroup。
        ttFeedAd.registerViewForInteraction((ViewGroup) nativeView, clickViewList, creativeViewList, new TTNativeAd.AdInteractionListener() {
            @Override
            public void onAdClicked(View view, TTNativeAd ad) {
                if (ad != null) {
                    Log.e(TAG, "广告" + ad.getTitle() + "被点击");
                }
            }

            @Override
            public void onAdCreativeClick(View view, TTNativeAd ad) {
                if (ad != null) {
                    Log.e(TAG, "广告" + ad.getTitle() + "被创意按钮被点击");
                }
            }

            @Override
            public void onAdShow(TTNativeAd ad) {
                if (ad != null) {
                    Log.e(TAG, "广告" + ad.getTitle() + "展示");
                }
            }
        });
    }

    private class TTFrameLayout extends FrameLayout {
        public TTFrameLayout(Context context) {
            super(context);
        }

        @Override
        public boolean dispatchTouchEvent(MotionEvent ev) {
            // 禁止滑动
            if (noScroll) {
                getParent().requestDisallowInterceptTouchEvent(true);
            }
            return super.dispatchTouchEvent(ev);
        }
    }
}
